package com.uenpay.im.panel;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.qiyunxin.android.http.view.ResizeLayout;
import com.qyx.android.weight.edittext.Emoji;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.panel.emoji.EmojiAdapter;
import com.uenpay.im.panel.emoji.OnEmojiSelected;
import com.uenpay.im.panel.emoji.QyxEmoji;

/**
 * @author SL
 * @created 2016-4-15 上午10:57:31
 * @copyRight http://www.qiyunxin.com
 * @function 只有Emoji面板管理
 */
public class FacePanelByEmojiManager {

	/**
	 * 计算软键盘高度
	 */
	private ResizeLayout mResizeLayout;
	private PanelManagerInterface.ISendTextListener mSendTextListener = null;
	private InputMethodManager inputManager;
	private EditText sendEdit;
	private Button sendBtn;
	private ImageView emojiBtn;
	private ViewPager emojiViewPager;
	private LinearLayout indexGroup;
	private int keyboardHeight = 0;
	private View action_view;
	private EmojiAdapter emojiAdapter;

	private Context mContext;

	public FacePanelByEmojiManager(Context _Context, View _View,
			ResizeLayout _ResizeLayout) {
		mResizeLayout = _ResizeLayout;
		mContext = _Context;
		initView(_View);
		showIndexMark(0);
	}

	private void initView(View view) {
		inputManager = (InputMethodManager) mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		sendEdit = (EditText) view.findViewById(R.id.editText);
		sendBtn = (Button) view.findViewById(R.id.send_btn);
		emojiBtn = (ImageView) view.findViewById(R.id.pic_switch_btn);
		emojiViewPager = (ViewPager) view.findViewById(R.id.emoji_list);
		indexGroup = (LinearLayout) view.findViewById(R.id.points_view);
		action_view = view.findViewById(R.id.emojis);
		mResizeLayout.setOnResizeListener(resizeListener);
		int tempHeight = IMApplication.config.getKeyBoardHeight();
		if (tempHeight != 0) {
			keyboardHeight = tempHeight;
			setFaceActionViewHeight();
		}
	}

	public void initListener() {
		emojiBtn.setOnClickListener(clickListener);
		/** 内容编辑框事件 **/
		sendEdit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				showSoftKeyboard();
//				try {
//					Thread.sleep(200);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//				sendEdit.setFocusable(true);
//				sendEdit.setFocusableInTouchMode(true);
//				sendEdit.requestFocus();
//				setActionViewDisplay(1);
//				emojiBtn.setImageResource(R.drawable.emoji);
				showFacePanelView();
			}
		});

		sendBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String content = sendEdit.getText().toString();
				if (mSendTextListener != null) {
					mSendTextListener.onSendTextContent(content);
				}
				sendEdit.setText("");
			}
		});
		sendEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (TextUtils.isEmpty(s)
						|| TextUtils.isEmpty(sendEdit.getText().toString()
								.trim())) {
					sendBtn.setVisibility(View.GONE);
					return;
				}
				if (count <= 0) {
					return;
				}

				/** 控制发送按钮和更多按钮的显示和隐藏 **/
				if (sendEdit.getText().toString().trim().length() > 0) {
					sendBtn.setVisibility(View.VISIBLE);
				} else {
					sendBtn.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	/**
	 * 表情按钮和更多按钮点击事件
	 */
	private final OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			sendEdit.setFocusable(true);
			sendEdit.setFocusableInTouchMode(true);
			sendEdit.requestFocus();
				if (action_view.getVisibility() == View.VISIBLE) {
					showSoftKeyboard();
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					setActionViewDisplay(1);
					emojiBtn.setBackgroundResource(R.drawable.emoji);
				} else {
					hideSoftKeyboard();
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					setActionViewDisplay(2);
					emojiBtn.setImageResource(R.drawable.ic_emoji_selector);
				}
			}
	};

	private void showSoftKeyboard() {
		((Activity) mContext).getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

		inputManager
				.showSoftInput(sendEdit, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	private void hideSoftKeyboard() {
		((Activity) mContext).getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

		if (inputManager.isActive()) {
			inputManager.hideSoftInputFromWindow(sendEdit.getWindowToken(), 0);
		}
	}

	/**
	 * 设置底部view显示隐藏状态
	 *
	 * @param type
	 */
	private void setActionViewDisplay(int type) {
		if (action_view != null) {
			if (type == 1) {
				action_view.setVisibility(View.GONE);
				emojiBtn.setImageResource(R.drawable.emoji);
			} else {
				action_view.setVisibility(View.VISIBLE);
			}
		}
	}

	/**
	 * 设置面板高度
	 *
	 */
	private void setFaceActionViewHeight() {
		LayoutParams faceParams = action_view.getLayoutParams();
		faceParams.height = keyboardHeight;
		action_view.setLayoutParams(faceParams);
	}

	/**
	 * 控制软键盘高度
	 */
	private ResizeLayout.OnResizeListener resizeListener = new ResizeLayout.OnResizeListener() {

		@Override
		public void OnResize(int w, int h, int oldw, int oldh) {
			if (oldw != 0 && oldh != 0) {
				if (h < oldh) {
					keyboardHeight = oldh - h;
					keyboardHeight = Math.max(dip2px(mContext, 240),
							keyboardHeight);
					IMApplication.config.setKeyBoardHeight(keyboardHeight);
					setFaceActionViewHeight();
				}
			}
		}
	};

	/**
	 * 把dip值转换成px值
	 */
	private int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	/**
	 * 初始化emoji事件
	 */
	private void initEmojiViewPageData() {
		emojiAdapter = new EmojiAdapter(mContext, new OnEmojiSelected() {
			@Override
			public void onEmojiSelected(Emoji emoji) {
				if (TextUtils.isEmpty(emoji.text)) {
					return;
				}

				int index = sendEdit.getSelectionStart();
				String text = sendEdit.getText().toString();
				String startString = text.substring(0, index);
				String endString = text.substring(index, text.length());
				String emojiText = "[" + emoji.text + "] ";

				sendEdit.setFocusable(true);
				sendEdit.setFocusableInTouchMode(true);
				sendEdit.requestFocus();
				sendEdit.setText(startString + emojiText + endString);
				sendEdit.setSelection(index + emojiText.length());
			}

			@Override
			public void onEmojiDeleted(Emoji emoji) {
				QyxEmoji.deleteEmoji(sendEdit, emoji.text);
			}
		});
		emojiViewPager.setAdapter(emojiAdapter);
		initViewPageLisenter();
	}

	/**
	 * 注册ViewPage滑动事件
	 *
	 */
	private void initViewPageLisenter() {
		emojiViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int index) {
				showIndexMark(index);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	/**
	 * 显示emoji或者gif标点
	 *
	 * @param index
	 */
	private void showIndexMark(int index) {
		if (index == 0) {
			initEmojiViewPageData();
		}
		if (emojiAdapter == null) {
			return;
		}
		int max = 0;
		max = emojiAdapter.getCount();
		indexGroup.removeAllViews();
		for (int i = 0; i < max; i++) {
			ImageView image = new ImageView(mContext);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			lp.leftMargin = 10;
			lp.rightMargin = 10;
			lp.topMargin = 5;
			lp.bottomMargin = 5;
			if (index == i) {
				image.setImageResource(R.drawable.point_selected);
			} else {
				image.setImageResource(R.drawable.point);
			}
			image.setLayoutParams(lp);
			indexGroup.addView(image);
		}

	}

	/**
	 * 发送按钮监听
	 *
	 * @param _SendTextListener
	 */
	public void onSendTextListener(PanelManagerInterface.ISendTextListener _SendTextListener) {
		mSendTextListener = _SendTextListener;
	}

	/**
	 * 隐藏面板
	 */
	public void hideFacePanelView(){
		if(action_view != null && emojiBtn != null){
			action_view.setVisibility(View.GONE);
			emojiBtn.setImageResource(R.drawable.emoji);
		}
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				hideSoftKeyboard();
			}
		}, 300);

	}

	/**
	 * 显示软键盘
	 */
	public void showFacePanelView(){
		showSoftKeyboard();
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		sendEdit.setFocusable(true);
		sendEdit.setFocusableInTouchMode(true);
		sendEdit.requestFocus();
		setActionViewDisplay(1);
		emojiBtn.setImageResource(R.drawable.emoji);
	}
}
